import * as ns from "@runtime";

type NS = typeof ns;
let _any = null as any;
/**
 * @see https://wails.io/zh-Hans/docs/reference/runtime/window
 * @see https://wails.io/zh-Hans/docs/reference/runtime/intro
 * 
 * @export
 * @param {string} func
 * @param {...any[]} args
 * @return {*} 
 */
export function call_runtime<K extends keyof NS, F extends NS[K]>(func: K, ...args: Parameters<F>[]): ReturnType<F> {
  const _any = call_runtime.obj();
  if (!_any)
    return Promise.reject(new Error('[call_runtime] runtime not exist')) as any

  const fn = _any[func];

  if (typeof fn !== 'function')
    return Promise.reject(new Error(`[wails_native_func] ${func} not exist`)) as any;

  return fn.call(_any, ...args);
}

call_runtime.obj = () => {
  if (_any === false) return false;
  return (_any = (window as any)?.runtime || false)
}